package com.lzx.resumeweb.api;

import com.lzx.resumebase.model.Result;
import com.lzx.resumebase.util.ResultUtil;
import com.lzx.resumeservice.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName OssApi
 * @Author 刘正星
 * @Date 2021/6/16 上午10:13
 * @Description
 */
@RestController
@Slf4j
@RequestMapping("/oss")
public class OssApi {


    @Autowired
    private OssService ossService;

    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file",required = false) MultipartFile multipartFile){

        String url = ossService.upload(multipartFile);

        return ResultUtil.success(url);
    }

    @PostMapping("/batchUpload")
    public Result batchUpload(@RequestParam(value = "file",required = false) MultipartFile[] multipartFile) throws InterruptedException {
        final long l = System.currentTimeMillis();
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        StringBuilder  stringBuilder = new StringBuilder();
        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < multipartFile.length; i++) {
            MultipartFile file = multipartFile[i];
            cachedThreadPool.execute(()->{
                String upload = ossService.upload(file);
                log.info(upload);
                stringBuffer.append(upload+" ");
                
            });
        }

        cachedThreadPool.shutdown();
        cachedThreadPool.awaitTermination(1, TimeUnit.DAYS);


//        for (int i = 0; i < multipartFile.length; i++) {
//            stringBuffer.append(ossService.upload(multipartFile[i]));
//            if (i!=multipartFile.length-1){
//                stringBuffer.append(" ");
//            }
//        }
        log.info(stringBuffer.toString());
        System.out.println("时间"+(System.currentTimeMillis()-l));
        return ResultUtil.success(stringBuffer.toString().trim());
    }

    @GetMapping("/del")
    public Result delFile(@RequestParam("name")String name){

        return ResultUtil.success(ossService.delete(name)) ;

    }
}
